﻿using System;
using System.Collections.Generic;
using System.Linq;
using LinqToTwitter;
using Microsoft.SystemCenter.Orchestrator.Integration;
using searchFilter = System.Linq.Expressions.Expression<System.Func<LinqToTwitter.DirectMessage, bool>>;

namespace SocialMediaIntegrationPack
{
    [Activity("Direct Messages Monitor")]
    [ActivityMonitor(Interval = 60)]
    public class DirectMessagesMonitorAct : GetDirectMessagesAct
    {
        private readonly HashSet<ulong> idCache;
        private readonly DateTime startTime;

        public DirectMessagesMonitorAct()
        {
            idCache = new HashSet<ulong>();
            startTime = DateTime.UtcNow;
        }

        /// <summary>
        /// Additional filter for Monitor that search for only newly added entries
        /// </summary>
        protected override IEnumerable<searchFilter> GetAdditionalFilters()
        {
            var filters = base.GetAdditionalFilters() ?? new List<searchFilter>();
            return filters.Concat(new List<searchFilter> {
                        dm => !idCache.Contains(dm.ID) && dm.CreatedAt.CompareTo(startTime) >= 0
                    });
        }

        /// <summary>
        /// Add all found messages to cache to prevent twice loading
        /// </summary>
        protected override void AfterSearchComplete(IQueryable<DirectMessage> result)
        {
            result.ToList().ForEach(dm => idCache.Add(dm.ID));
        }
    }
}